Skip to content

RadioDelegate

Base classes

Name Children Inherits
StyledItemDelegate
prettyqt.widgets.styleditemdelegate

⋔ Inheritance diagram

graph TD
  935693270["itemdelegates.RadioDelegate"]
  4109708588["widgets.StyledItemDelegate"]
  3153451512["widgets.AbstractItemDelegateMixin"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  3599391368["QtWidgets.QStyledItemDelegate"]
  475576970["QtWidgets.QAbstractItemDelegate"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  4109708588 --> 935693270
  3153451512 --> 4109708588
  3227531497 --> 3153451512
  2751680898 --> 3227531497
  2751680898 --> 3153451512
  3599391368 --> 4109708588
  475576970 --> 3599391368
  3984060476 --> 475576970
  37984305 --> 3984060476
  2751680898 --> 37984305

🛈 DocStrings

Bases: StyledItemDelegate

Source code in prettyqt/itemdelegates/radiodelegate.py
class RadioDelegate(widgets.StyledItemDelegate):
    ID = "radio"

    def __init__(self, parent: widgets.QWidget, items: Iterable[str]):
        super().__init__(parent)
        self.items = list(items)
        self.choices: list[int | None] = [None for _ in self.items]

    def createEditor(
        self,
        parent: widgets.QWidget,
        option: widgets.QStyleOptionViewItem,
        index: core.ModelIndex,
    ) -> widgets.Widget:
        editor = _RadioEditor(parent=parent, margin=0, auto_fill_background=True)
        # create a button group to keep track of the checked radio
        editor.button_group = widgets.ButtonGroup()
        # adding the widget as an argument to the layout constructor automatically
        # applies it to the widget
        layout = editor.set_layout("horizontal", margin=0)
        for i, k in enumerate(self.items):
            rb = widgets.RadioButton(k)
            layout.addWidget(rb)
            # prevent the radio to get focus from keyboard or mouse
            rb.set_focus_policy("none")
            rb.installEventFilter(self)
            editor.button_group.addButton(rb, i)
        # add a stretch to always align contents to the left
        layout.addStretch(1)

        # set a property that will be used for the mask
        editor.setProperty("offMask", gui.Region(editor.rect()))
        editor.installEventFilter(self)
        return editor

    def eventFilter(self, source: core.QObject, event: core.QEvent) -> bool:
        if not isinstance(source, widgets.QWidget):
            return super().eventFilter(source, event)
        match event.type():
            case core.Event.Type.MouseButtonPress:
                if isinstance(source, widgets.QRadioButton):
                    container = source.parentWidget()
                    if container is not None and not container.hasFocus():
                        # the parent has no focus, set it and ignore the click
                        container.setFocus()
                        return True
                elif not source.hasFocus():
                    # the container has been clicked, check
                    source.setFocus()
            case core.Event.Type.FocusIn:
                # event received as a consequence of setFocus
                # clear the mask to show it completely
                source.clearMask()
            case core.Event.Type.FocusOut:
                # another widget has requested focus, set the mask
                if (mask := source.property("offMask")) is not None:
                    source.setMask(mask)
                # update the table viewport to get rid of possible
                # grid lines left after masking
                if (container := source.parentWidget()) is not None:
                    container.update()
        return super().eventFilter(source, event)

    def updateEditorGeometry(
        self,
        editor: widgets.QWidget,
        option: widgets.QStyleOptionViewItem,
        index: core.ModelIndex,
    ):
        rect = core.Rect(option.rect)
        min_width = editor.minimumSizeHint().width()
        if rect.width() < min_width:
            rect.setWidth(min_width)
        editor.setGeometry(rect)
        # create a new mask based on the option rectangle, then apply it
        mask = gui.Region(0, 0, option.rect.width(), option.rect.height())
        editor.setProperty("offMask", mask)
        editor.setMask(mask)

    def setEditorData(self, editor: widgets.QWidget, index: core.ModelIndex):
        value = index.data(constants.DISPLAY_ROLE)
        if value in self.items:
            group = cast("_RadioEditor", editor).button_group
            if (button := group.button(self.items.index(value))) is not None:
                button.setChecked(True)

    def setModelData(
        self,
        editor: widgets.QWidget,
        model: core.QAbstractItemModel,
        index: core.ModelIndex,
    ):
        button = cast("_RadioEditor", editor).button_group.checkedId()
        if button >= 0:
            model.setData(
                index,
                self.items[button],
                constants.EDIT_ROLE,
            )
            self.choices[button] = index.row()

:fa-brands-github: Show source on GitHub